package com.jiamao.goplay.ui.discover;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.gyf.immersionbar.ImmersionBar;
import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.adapter.CityMenuAdapter;
import com.jiamao.goplay.adapter.CityTextListAdapter;
import com.jiamao.goplay.app.AppViewModelFactory;
import com.jiamao.goplay.base.BaseMVVMFragment;
import com.jiamao.goplay.databinding.DiscoverCityLayoutBinding;
import com.jiamao.goplay.ui.discover.vm.CityItemVM;
import com.jiamao.goplay.ui.discover.vm.CityVM;
import com.netease.nim.uikit.common.util.C;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * 城市选择
 */
public class CityFragment extends BaseMVVMFragment<DiscoverCityLayoutBinding, CityVM> {


    private CityMenuAdapter cityMenuAdapter;
    private ArrayList hostList = new ArrayList();
    private  ArrayList asirArrayList = new ArrayList(); //亚洲
    private  ArrayList eopuArrayList = new ArrayList(); //欧洲
    private  ArrayList usArrayList = new ArrayList(); //北美
    private  ArrayList nsArrayList = new ArrayList(); //南北美
    private  ArrayList ausArrayList = new ArrayList(); //大洋洲
    private  ArrayList fzArrayList = new ArrayList(); //非洲
    private String cityJson;

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public CityVM initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(CityVM.class);
    }
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.discover_city_layout;
    }
    public void initDatas(){

        hostList.add("北京");
        hostList.add("上海");
        hostList.add("广州");
        hostList.add("深圳");
        hostList.add("杭州");
        hostList.add("武汉");
        hostList.add("长沙");
        hostList.add("成都");
        hostList.add("重庆");
        hostList.add("西安");
        hostList.add("南京");
        hostList.add("三亚");
        hostList.add("厦门");
        hostList.add("苏州");
        hostList.add("天津");
        hostList.add("郑州");
        hostList.add("哈尔滨");
        hostList.add("昆明");
        hostList.add("香港");
        hostList.add("澳门");
        hostList.add("台湾");

       String json =  getOriginalFundData(getContext(),"gj.json");
         cityJson =  getOriginalFundData(getContext(),"city.json");
        try {
            JSONArray jsonArray = new JSONArray(json);
            for (int i=0;i<jsonArray.length();i++){
                JSONObject jb = jsonArray.optJSONObject(i);
               String name =  jb.getString("country_cname");
               if (name.equals("中国") || name.equals("香港") || name.equals("澳门") || name.equals("台湾") ){
                   continue;
               }
                switch (jb.getString("continent_cname")){
                    case "欧洲":
                        eopuArrayList.add(name);
                        break;
                    case "亚洲":
                        asirArrayList.add(name);
                        break;
                    case "非洲":
                        fzArrayList.add(name);
                        break;
                    case "北美洲":
                        usArrayList.add(name);
                        break;
                        case "南美洲":
                            nsArrayList.add(name);
                        break;
                    case "大洋洲":
                        ausArrayList.add(name);
                        break;
                }


            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        asirArrayList.add("");
    }

    public  String getOriginalFundData(Context context,String name) {
        InputStream input = null;
        try {
            //taipingyang.json文件名称
            input = context.getAssets().open(name);
            String json = convertStreamToString(input);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * input 流转换为字符串
     *
     * @param is
     * @return
     */
    private  String convertStreamToString(InputStream is) {
        String s = null;
        try {
            //格式转换
            Scanner scanner = new Scanner(is, "UTF-8").useDelimiter("\\A");
            if (scanner.hasNext()) {
                s = scanner.next();
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

    @Override
    public void initViewObservable() {

        viewModel.uc.pSwitchEvent.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String aBoolean) {
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标
                refreshData(aBoolean);

            }
        });
        viewModel.uc.setGrid.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String aBoolean) {
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标

            }
        });

    }

    @Override
    public void initData() {
        super.initData();
        initDatas();
        cityMenuAdapter = new CityMenuAdapter(getContext());
         binding.setAdapter(cityMenuAdapter);
        binding.setAdapter2(new CityTextListAdapter(getContext()));

        ImmersionBar.with(this). keyboardEnable(false).statusBarDarkFont(true).titleBar(binding.getRoot().findViewById(R.id.toolbar)).init();
        TextView titleTv =  binding.getRoot().findViewById(R.id.tvTitle);
        titleTv.setText("选择国家/城市");
        binding.getRoot().findViewById(R.id.ll_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
    }


    public void refreshData(String name){
        if (name.equals("中国")){
            viewModel.observableArrayList.clear();

            viewModel.observableArrayList.add(new CityItemVM(viewModel,"热门城市",hostList));

            try {
                JSONArray jsonArray = new JSONArray(cityJson);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jb = jsonArray.optJSONObject(i);
                    String cityname = jb.getString("name");
                    if (cityname.equals("北京市") || cityname.equals("天津市") || cityname.equals("重庆市") || cityname.equals("上海市")) {

                        continue;
                    }
                 JSONArray cities = jb.getJSONArray("cities");
                    ArrayList list = new ArrayList();
                    for (int q = 0; q < cities.length(); q++){
                        list.add(cities.getJSONObject(q).getString("name"));
                    }
                    viewModel.observableArrayList.add(new CityItemVM(viewModel,cityname,list));
                }
            }catch (Exception e){

            }

        }
        else if(name.equals("亚洲")) {
            viewModel.observableArrayList.clear();

            viewModel.observableArrayList.add(new CityItemVM(viewModel,"全部国家",asirArrayList));
            //  binding.recyclerview.notifyAll();

        }
        else if(name.equals("欧洲")) {
            viewModel.observableArrayList.clear();

            viewModel.observableArrayList.add(new CityItemVM(viewModel,"全部国家",eopuArrayList));
            //  binding.recyclerview.notifyAll();

        }
        else if(name.equals("非洲")) {
            viewModel.observableArrayList.clear();

            viewModel.observableArrayList.add(new CityItemVM(viewModel,"全部国家",fzArrayList));
            //  binding.recyclerview.notifyAll();

        }
        else if(name.equals("北美洲")) {
            viewModel.observableArrayList.clear();

            viewModel.observableArrayList.add(new CityItemVM(viewModel,"全部国家",usArrayList));
            //  binding.recyclerview.notifyAll();

        }
        else if(name.equals("南美洲")) {
            viewModel.observableArrayList.clear();

            viewModel.observableArrayList.add(new CityItemVM(viewModel,"全部国家",nsArrayList));
            //  binding.recyclerview.notifyAll();

        }
        else if(name.equals("大洋洲")) {
            viewModel.observableArrayList.clear();

            viewModel.observableArrayList.add(new CityItemVM(viewModel,"全部国家",ausArrayList));
            //  binding.recyclerview.notifyAll();

        }

    }


}
